<template>
  <div class="rule-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>内容替换规则</span>
          <el-button type="primary" @click="showAddDialog" :icon="Plus">
            添加规则
          </el-button>
        </div>
      </template>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button @click="fetchRules" :icon="Refresh">刷新</el-button>
        <el-button @click="showTestDialog = true" :icon="DocumentChecked">测试规则</el-button>
      </div>

      <!-- 规则表格 -->
      <el-table
          :data="ruleStore.rules"
          :loading="ruleStore.loading"
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="ruleName" label="规则名称" width="150" />
        <el-table-column prop="sourceText" label="原文本" min-width="150" show-overflow-tooltip />
        <el-table-column prop="targetText" label="替换文本" min-width="150" show-overflow-tooltip />
        <el-table-column prop="ruleType" label="规则类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getRuleTypeTag(row.ruleType)">
              {{ getRuleTypeText(row.ruleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
                v-model="row.enabled"
                @change="toggleRule(row.id, row.enabled)"
                active-text="启用"
                inactive-text="禁用"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="editRule(row)"
                :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="deleteRule(row.id)"
                :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
        v-model="showRuleDialog"
        :title="editingRule ? '编辑规则' : '添加规则'"
        width="600px"
    >
      <el-form :model="ruleForm" :rules="ruleRules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="原文本" prop="sourceText">
          <el-input
              v-model="ruleForm.sourceText"
              type="textarea"
              :rows="3"
              placeholder="请输入要替换的原文本"
          />
        </el-form-item>
        <el-form-item label="替换文本" prop="targetText">
          <el-input
              v-model="ruleForm.targetText"
              type="textarea"
              :rows="3"
              placeholder="请输入替换后的文本（为空则删除原文本）"
          />
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="ruleForm.ruleType" placeholder="请选择规则类型">
            <el-option label="精确匹配" :value="1" />
            <el-option label="正则表达式" :value="2" />
            <el-option label="包含匹配" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="ruleForm.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="ruleForm.enabled" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="ruleForm.description"
              type="textarea"
              :rows="2"
              placeholder="请输入规则描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRuleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRule" :loading="saving">
          {{ editingRule ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 测试规则对话框 -->
    <el-dialog v-model="showTestDialog" title="测试替换规则" width="800px">
      <el-form label-width="100px">
        <el-form-item label="测试内容">
          <el-input
              v-model="testContent"
              type="textarea"
              :rows="5"
              placeholder="请输入要测试的内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="testRules" :loading="testing">
            测试规则
          </el-button>
        </el-form-item>
        <el-form-item v-if="testResult" label="处理结果">
          <div class="test-result">
            <h4>原始内容：</h4>
            <pre class="content-box">{{ testResult.original }}</pre>
            <h4>处理后内容：</h4>
            <pre class="content-box">{{ testResult.processed }}</pre>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRuleStore } from '@/stores/rule'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  DocumentChecked,
  Edit,
  Delete
} from '@element-plus/icons-vue'

const ruleStore = useRuleStore()

// 对话框状态
const showRuleDialog = ref(false)
const showTestDialog = ref(false)
const editingRule = ref(null)
const saving = ref(false)
const testing = ref(false)

// 表单数据
const ruleForm = reactive({
  ruleName: '',
  sourceText: '',
  targetText: '',
  ruleType: 1,
  enabled: true,
  sortOrder: 0,
  description: ''
})

// 测试相关
const testContent = ref('')
const testResult = ref(null)

// 表单验证规则
const ruleRules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  sourceText: [
    { required: true, message: '请输入原文本', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ]
}

const ruleFormRef = ref()

// 获取规则类型标签样式
const getRuleTypeTag = (type) => {
  const tags = { 1: 'primary', 2: 'warning', 3: 'success' }
  return tags[type] || 'info'
}

// 获取规则类型文本
const getRuleTypeText = (type) => {
  const texts = { 1: '精确匹配', 2: '正则表达式', 3: '包含匹配' }
  return texts[type] || '未知'
}

// 获取规则列表
const fetchRules = async () => {
  await ruleStore.fetchRules()
}

// 显示添加对话框
const showAddDialog = () => {
  editingRule.value = null
  resetForm()
  showRuleDialog.value = true
}

// 编辑规则
const editRule = (rule) => {
  editingRule.value = rule
  Object.assign(ruleForm, {
    ruleName: rule.ruleName,
    sourceText: rule.sourceText,
    targetText: rule.targetText || '',
    ruleType: rule.ruleType,
    enabled: rule.enabled,
    sortOrder: rule.sortOrder || 0,
    description: rule.description || ''
  })
  showRuleDialog.value = true
}

// 保存规则
const saveRule = async () => {
  try {
    await ruleFormRef.value.validate()

    saving.value = true

    if (editingRule.value) {
      await ruleStore.updateRule(editingRule.value.id, ruleForm)
      ElMessage.success('规则更新成功')
    } else {
      await ruleStore.createRule(ruleForm)
      ElMessage.success('规则创建成功')
    }

    showRuleDialog.value = false
  } catch (error) {
    console.error('保存规则失败:', error)
  } finally {
    saving.value = false
  }
}

// 删除规则
const deleteRule = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除这条规则吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await ruleStore.deleteRule(id)
    ElMessage.success('规则删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除规则失败')
    }
  }
}

// 切换规则状态
const toggleRule = async (id, enabled) => {
  try {
    await ruleStore.toggleRule(id, enabled)
    ElMessage.success(`规则已${enabled ? '启用' : '禁用'}`)
  } catch (error) {
    ElMessage.error('状态切换失败')
    await fetchRules() // 刷新列表恢复状态
  }
}

// 测试规则
const testRules = async () => {
  if (!testContent.value.trim()) {
    ElMessage.warning('请输入测试内容')
    return
  }

  testing.value = true
  try {
    const result = await ruleStore.testRules(testContent.value)
    testResult.value = result.data
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    testing.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(ruleForm, {
    ruleName: '',
    sourceText: '',
    targetText: '',
    ruleType: 1,
    enabled: true,
    sortOrder: 0,
    description: ''
  })
  ruleFormRef.value?.clearValidate()
}

onMounted(() => {
  fetchRules()
})
</script>

<style scoped>
.rule-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .toolbar {
    margin-bottom: 20px;
  }

  .test-result {
    .content-box {
      background-color: #f5f7fa;
      padding: 15px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      white-space: pre-wrap;
      word-wrap: break-word;
      margin: 10px 0;
    }
  }
}
</style>